/**
 * Created by jt on 2017/5/8.
 */
import "./index.less";
import "../../../unit/common/js/bootstrap_js/select2.min.js";
import "../../../unit/common/js/bootstrap_js/jquery.dataTables.js";
import "../../../unit/common/js/bootstrap_js/form-samples.js";
import "../../../unit/common/js/bootstrap_js/table-editable.js";

import {pubFlg,artclTypCod} from "../config.js";
import articleListTpl from "./getArticle.handlebars";
import paginationTpl from "./paging.handlebars";

    var token = sessionStorage.getItem('token');
    if (token == null || token =='') {
        location.href = HOST_FRT+'/logins/login.html';
    }

var articleList = {
    pageNo: 1,
    pageSize: 20,
    maxPage: 1,
    isFirstPage: false,
    isLastPage: false,
    total: 0,
    init: function(){
        this.getArticleData()
            .then(this.renderarticleList)
            .then(this.renderPagination)
            .then(this.bindEvent);
    },
    getArticleData: function() {
        return new Promise((resolve, reject)=>{
            let self = this;
            let data ={};
            $.ajax({
                url: HOST_ADDR + `/cpmp/artcl/queryByConds/${self.pageNo}/${self.pageSize}`,
                type: 'post',
                dataType: 'json',
                headers: {
                    'access_token': token,'login_type':'ums'
                },
                data:JSON.stringify(data),
                contentType: "application/json",
                success: function (resp) {
                    if (resp.success) {
                        console.log(resp);
                        resolve(resp);
                    }
                    else {
                        alert(resp.msgInf);
                    }
                },
                error: function (err) {
                    console.log(err);
                }
            });


        });

    },
    // 渲染列表

    renderarticleList: function(resp){
        let self = articleList;
        // 处理数据begin
        self.total = resp.data.count;
        self.isFirstPage = self.pageNo === 1;
        self.maxPage = Math.ceil(self.total / self.pageSize);
        $.each(resp.data.list,function(index,item){
            item.pubFlgFmt = pubFlg[item.pubFlg] || '暂无状态';
            item.artclTypCodFmt = artclTypCod[item.artclTypCod] || '暂无状态';
            item.editAvailabel = (item.pubFlg == '0');
            item.pubAvailabel = (item.pubFlg == '0');
            item.recallAvailabel = (item.pubFlg == '1');
        });
        // 处理数据end
        if(self.pageNo * self.pageSize >= self.total){
            self.isLastPage = true;
        }else{
            self.isLastPage = false;
        }

        let resultHtml = articleListTpl({articleList: resp.data.list});
        $('tbody').html(resultHtml);
    },

    // 渲染分页
    renderPagination: function(){
        let self = articleList;
        let pageList = [];
        for(let i=0; i<self.maxPage; i++){
            pageList.push({idx: i+1});
        }
        console.log(self.total);
        let paginationHtml = paginationTpl({
            begin: (self.pageNo-1) * self.pageSize + 1,
            end: self.isLastPage ? self.total : self.pageNo * self.pageSize,
            total: self.total,
            isLastPage: self.isLastPage,
            isFirstPage: self.isFirstPage,
            pageList: pageList

        });
        $('.J_pagination').html(paginationHtml);
        $('.page-item').each((index,item)=>{
            if($(item).data('index')===self.pageNo){
                console.log(this);
                $(item).addClass('active');
            }
            //最多显示7个页码
            if (Math.abs($(item).data('index')-self.pageNo) > 3) {
                $(item).css('display','none');
            }
        });
    },

    // 绑定事件
    bindEvent: function(){
        let self = articleList;
        $('.J_prev').unbind().click(function(){
            if(self.pageNo > 1){
                self.pageNo = self.pageNo -1;
                self.renderList();
            }
        });
        $('.J_next').unbind().click(function(){
            if(self.pageNo < self.maxPage){
                self.pageNo = self.pageNo + 1;
                self.renderList();
            }

        });

        //首尾页
        $('.isFirst').unbind().click(function(){
            if(self.pageNo != 1){
                self.pageNo = 1;
                self.renderList();
            }
        });
        $('.isLast').unbind().click(function(){
            if(self.pageNo != self.maxPage){
                self.pageNo = self.maxPage;
                self.renderList();
            }
        });

        $('.page-item').unbind().click(function(){
            let $item = $(this);

            if(!$item.hasClass('active')){
                self.pageNo = $item.data('index');
                self.renderList();
            }
        });

        //删除整行
        jQuery('.delete').click(function () {
            var _this = jQuery(this);
            var artclId = _this.parent('td').siblings('td').eq(0).text();
            // alert(projId)
            jQuery.ajax({
                url: HOST_ADDR+'/cpmp/artcl/del/'+artclId,
                type: 'get',
                // data: JSON.stringify(data),
                dataType: 'json',
                contentType:"application/json",
                headers: {
                    'access_token': token,'login_type':'ums'
                },
                success: function(resp){
                    if (!resp.success) {
                        alert(resp.msgCod+' '+resp.msgInf);
                        return;
                    }
                    // console.log(resp);
                    alert('成功删除！');
                    location.reload();
                },
                error:function(err){
                    console.log(err);
                }
            });
        });

        //发布文章
        jQuery('.sharePro').click(function () {
            var _this = jQuery(this);
            jQuery('.fade').css('display','none');
            jQuery('#shareProject').css('display','block');
            jQuery('.shareOk').click(function () {
                var artclId = _this.parent('td').siblings('td').eq(0).text();
                // alert(projId)
                jQuery.ajax({
                    url: HOST_ADDR+'/cpmp/artcl/pub/'+artclId,
                    type: 'get',
                    // data: JSON.stringify(data),
                    dataType: 'json',
                    contentType:"application/json",
                    headers: {
                        'access_token': token,'login_type':'ums'
                    },
                    success: function(resp){
                        if (!resp.success) {
                            alert(resp.msgCod+' '+resp.msgInf);
                            return;
                        }
                        // console.log(resp);
                        alert('发布公告成功！');
                        location.reload();
                    },
                    error:function(err){
                        console.log(err);
                    }
                });
            });
        });

        //撤回文章
        jQuery('.recallPro').click(function () {
            var _this = jQuery(this);
            jQuery('.fade').css('display','none');
            jQuery('#recallProject').css('display','block');
            jQuery('.recallOk').click(function () {
                var artclId = _this.parent('td').siblings('td').eq(0).text();
                // alert(projId)
                jQuery.ajax({
                    url: HOST_ADDR+'/cpmp/artcl/cclPub/'+artclId,
                    type: 'get',
                    // data: JSON.stringify(data),
                    dataType: 'json',
                    contentType:"application/json",
                    headers: {
                        'access_token': token,'login_type':'ums'
                    },
                    success: function(resp){
                        if (!resp.success) {
                            alert(resp.msgCod+' '+resp.msgInf);
                            return;
                        }
                        // console.log(resp);
                        alert('文章成功撤回！');
                        location.reload();
                    },
                    error:function(err){
                        console.log(err);
                    }
                });
            });
        });
    },

    // 渲染列表
    renderList(){
        this.getArticleData()
            .then(this.renderarticleList)
            .then(this.renderPagination)
            .then(this.bindEvent);
    }
};

App.init();
articleList.init();
jQuery('.logOut').attr('href','../logins/login.html');
